package com.mairuide._frame.config;

import com.mairuide._frame.exception.AuthorizationCodeException;
import com.mairuide._frame.exception.DiskException;
import com.mairuide._frame.exception.TimeExpireException;
import com.mairuide._frame.exception.TimeNotFoundException;
import com.mairuide._frame.utils.*;
import com.mairuide.httpclient.BaseSite;
import com.mairuide.platmanager.PlatManager;
import com.mairuide.platmanager.PlatManagerService;
import com.mairuide.version_up.service.CompanyService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private PlatManagerService platManagerService;
	@Autowired
	private StringEncryptor encryptor;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	CompanyService companyService;
	@Autowired
	private BaseSite baseSite;
	@Autowired
	private HttpSession session;
	@Resource
	protected HttpServletRequest request;
	@Override
	public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
		String absPath = new File("").getAbsolutePath();
		if (StringUtils.endsWith(absPath,"\\lib")){
			String[] split = absPath.split("\\\\");
			List<String> asList = Arrays.asList(split);
			List<String> subList = asList.subList(0, asList.size() - 1);
			absPath=StringUtils.join(subList,"\\");
		}
		System.out.println("<<<<<<<<<<<<<<<<<<"+ absPath);
		//得到项目绝对路径
		//String absPath = System.getProperty("user.dir");
		/*System.out.println("得到项目绝对路径："+absPath);
		//分隔成字符串数组
		String[] split = absPath.split("\\\\");
		//数组转换成集合
		List<String> asList = Arrays.asList(split);
		//截取掉最后一个元素，因为是和项目同级目录
		List<String> subList = asList.subList(0, asList.size() - 1);
		//获取到授权码绝对路径
		String path=StringUtils.join(subList,"\\")+"\\mrd.properties";*/
		String path=absPath+"\\listener.mrd";
		//获取授权码
		List lines = null;
		try {
			lines = FileUtils.readLines(new File(path), "UTF-8");
		} catch (IOException e) {
			logger.info("读取授权文件异常");
			e.printStackTrace();
		}
		String authorizationCode = StringUtils.join(lines,"");
		//String authorizationCode = ReadPropertiesConfig.read("authorization-code", path);
		if (authorizationCode==null){
			logger.info("授权码没有获取到");
			throw  new AuthorizationCodeException("授权码没有获取到");
		}
		//获取私钥
		String privateKey = ReadPropertiesConfig.read("privateKey");
		//解密
		String decryptData = null;
		try {
			decryptData = RSAUtils.decryptByPrivateKey(authorizationCode, privateKey);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("RSA非对称加密 -- 》解密失败");
		}
		//验证机器码是否正确
		int i = decryptData.indexOf("(");
		String substring = decryptData.substring(0, i);
		if(i==-1){
			logger.info("授权码没有取到时间");
			throw new TimeNotFoundException("授权码没有取到时间");
		}
		String decrypt = AESUtil.decrypt(substring,"MRD-7800");
		String diskId = DiskUtils.getDiskId();
		if (!diskId.equals(decrypt)){
			logger.info("验证错误，可能不是在本机操作");
			throw new DiskException("验证错误，可能不是在本机操作");
		}
		//获取时间
		String time =null;
		String reg=".+(\\d{4}-\\d{2}-\\d{2})";
		List matcher = RegUtil.getMatcher(reg, decryptData);
		if (matcher.size()>0){
			time=matcher.get(0).toString();
		}else{
			logger.info("授权码没有取到时间");
			throw new TimeNotFoundException("授权码没有取到时间");
		}
		//验证是否过期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(sdf.format(new Date()).compareTo(time)>0){
			logger.info("时间过期");
			throw new TimeExpireException("时间过期");
		}
		PlatManager user = platManagerService.findByLoginName(arg0.trim());
		if (user == null)
			throw new UsernameNotFoundException("username not found");

		/* 上面的 findByLoginName 返回的字段不全，这里先再用ID查询一次吧 */
		user = platManagerService.findOne(user.getId());
		LoginUser loginUser = new LoginUser(user);
		return loginUser;
	}

}
